package sysman;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import util.DateUtil;

import common.constant.LoginConst;
import common.serialization.IWebText;
import common.serialization.StringWebText;
import common.serialization.XmlDataBean;
import common.service.CacheService;
import common.service.ICacheService;
import common.service.IService;
import common.service.ServiceFactory;
import common.web.WebHelper;

/**
 * 
 * 系统管理页面控制类
 *
 */
public class SysmanAction {
	private final static String USER_CODE_ADMIN = "a";//超级管理员的帐号
	
	//根据用户查找对应的角色
	private static String getRoleIdByUserId(IService service, HttpServletRequest request) throws Exception {
		String roleId = null;
		@SuppressWarnings("unchecked")
		Map<String, Object> loginUser = (Map<String, Object>) request.getSession().getAttribute(LoginConst.SESSION_USER);
		if(loginUser != null && !loginUser.isEmpty()) {
			String userId = (String)loginUser.get("USER_ID");
			//根据用户ID查询角色ID
			Map<String, Object> relMap = service.queryById("select * from SYSMAN_USER_ROLE where USER_ID='" + userId + "' ");
			if(relMap != null && !relMap.isEmpty()) {
				roleId = (String)relMap.get("ROLE_ID");
			}
		}
		return roleId;
	}
	
	//获取用户帐号
	private static String getLoginUserCode(HttpServletRequest request) throws Exception {
		String userCode = null;
		@SuppressWarnings("unchecked")
		Map<String, Object> loginUser = (Map<String, Object>) request.getSession().getAttribute(LoginConst.SESSION_USER);
		if(loginUser != null && !loginUser.isEmpty()) {
			userCode = (String)loginUser.get("USER_CODE");
		}
		return userCode;
	}
	
	//获取第一级的菜单
	public static List<Map<String, Object>> getFirstMenu(HttpServletRequest request) throws Exception {
		IService service = ServiceFactory.getService(null);
		String userCode = getLoginUserCode(request);
		String roleId = getRoleIdByUserId(service, request);
		if(USER_CODE_ADMIN.equals(userCode) || roleId != null) {
			String sql = "select * from SYSMAN_RIGHT where ENABLED=1 and PID='0' ";
			if(roleId != null && !USER_CODE_ADMIN.equals(userCode)) {//角色权限
				sql += "and ID in (select RIGHT_ID from SYSMAN_ROLE_RIGHT where ROLE_ID='" + roleId + "' ) ";
			}
			sql += "order by TREE_ORDER";
			List<Map<String, Object>> list = service.queryBySql(sql);
			request.setAttribute("menuList", list);
			return list;
		}
		return null;
	}
	
	//根据父ID查询菜单数据
	public static IWebText getMenuByPid(String pid, HttpServletRequest request) throws Exception {
		XmlDataBean root = new XmlDataBean();
		root.setNameSpace("tree");
		root.setId("0");
		
		IService service = ServiceFactory.getService(null);
		String userCode = getLoginUserCode(request);
		String roleId = getRoleIdByUserId(service, request);
		if(USER_CODE_ADMIN.equals(userCode) || roleId != null) {
			String sql = "select * from SYSMAN_RIGHT where ENABLED=1 and PID='" + pid + "' ";
			if(roleId != null && !USER_CODE_ADMIN.equals(userCode)) {//角色权限
				sql += "and ID in (select RIGHT_ID from SYSMAN_ROLE_RIGHT where ROLE_ID='" + roleId + "' ) ";
			}
			sql += "order by TREE_ORDER";
			List<Map<String,Object>> list = service.queryBySql(sql );
			for(Map<String,Object> map : list) {
				String id = (String)map.get("ID");
				
				XmlDataBean child = new XmlDataBean();
				child.setNameSpace("item");
				child.setId(id);
				child.setAttribute("text", (String)map.get("NAME"));
				
				//设置url
				XmlDataBean url = new XmlDataBean();
				url.setNameSpace("userdata");
				url.setAttribute("name", "url");
				url.setText((String)map.get("RIGHT_URL"));
				child.appendChildXmlDataBean(url);
				
				root.appendChildXmlDataBean(child);
			}
		}
		return root;
	}
	
	//获取缓存的配置数据
	public static List<Map<String,Object>> getCacheListData(HttpServletRequest request) throws Exception {
		ICacheService service = (ICacheService) ServiceFactory.getService(new CacheService());
		
		String operate = request.getParameter("operate");
		if("refreshCache".equals(operate)) {//刷新缓存
			String cacheId = request.getParameter("cacheId");
			if(StringUtils.isEmpty(cacheId)) {//刷新所有缓存数据
				service.initAllCacheData();
			} else {//根据缓存ID刷新缓存数据
				service.refreshByCacheId(cacheId);
			}
		}
		
		//获取缓存配置数据
		List<Map<String,Object>> pageList = service.getAllCacheConfig();
		request.setAttribute("pageList", pageList);
		
		return pageList;
	}
	
	//刷新缓存
	public static void refreshCacheData(String cacheId) throws Exception {
		ICacheService service = (ICacheService) ServiceFactory.getService(new CacheService());
		if(StringUtils.isEmpty(cacheId)) {//刷新所有缓存数据
			service.initAllCacheData();
		} else {//根据缓存ID刷新缓存数据
			service.refreshByCacheId(cacheId);
		}
	}
	
	//登陆
	public static void login(HttpServletRequest request) throws Exception {
		String userCode = request.getParameter("USER_CODE");
		String pwd = request.getParameter("PASSWORD");
		
		String codeImage = (String)request.getSession().getAttribute("codeImage");
		String codeImage2 = request.getParameter("codeImage");
		if(!codeImage.equals(codeImage2)) {
			request.setAttribute("ERROR", "1");
		}
		
		IService service = ServiceFactory.getService(null);
		Map<String,Object> loginMap = service.queryById("select * from SYSMAN_USER where ENABLED=1 and USER_CODE=? and USER_PWD=? ", new Object[]{userCode,pwd} );
		if(loginMap != null && !loginMap.isEmpty()) {
			request.getSession().setAttribute(LoginConst.SESSION_USER, loginMap);
			
			//记录登录日志
			String userId = (String)loginMap.get("USER_ID");
			service.executeBySql("update SYSMAN_USER set LOGIN_NUM=coalesce(LOGIN_NUM,0)+1, LOGIN_TIME='" + DateUtil.dateToString(new Date()) + "' where USER_ID='" + userId + "'");
		} else {
			request.setAttribute("ERROR", "2");
		}
	}
	
	//登出
	public static void logout(HttpServletRequest request) throws Exception {
		request.getSession().setAttribute(LoginConst.SESSION_USER, null);
	}
	
	//保存角色和用户的关系
	public IWebText doSaveRoleUser(WebHelper webHelper) {
		StringWebText swt = new StringWebText();
		
		HttpServletRequest request = webHelper.getRequest();
		String roleId = request.getParameter("roleId");
		String userIds = request.getParameter("userIds");
		String[] userIdArr = userIds.split(",");
		int len = userIdArr.length;
		List<Object[]> parameterList = new ArrayList<Object[]>();
		for(int i = 0;i<len;i++) {
			Object[] paraArr = new Object[]{roleId, userIdArr[i]};
			parameterList.add(paraArr);
		}
		
		IService service = ServiceFactory.getService(null);
		try {
			service.executeBySql("delete from SYSMAN_USER_ROLE where ROLE_ID='" + roleId + "'");
			service.executeBatchBySql("insert into SYSMAN_USER_ROLE(ROLE_ID,USER_ID) values(?,?)", parameterList);
			swt.setValue("1");
		} catch (Exception e) {
			e.printStackTrace();
			swt.setValue("0");
		}
		return swt;
	}
	
	//保存角色与权限的关系
	public IWebText doSaveRoleRight(WebHelper webHelper) {
		StringWebText swt = new StringWebText();
		
		HttpServletRequest request = webHelper.getRequest();
		String roleId = request.getParameter("roleId");
		String rightIds = request.getParameter("rightIds");
		String[] rightIdArr = rightIds.split(",");
		int len = rightIdArr.length;
		List<Object[]> parameterList = new ArrayList<Object[]>();
		for(int i = 0;i<len;i++) {
			Object[] paraArr = new Object[]{roleId, rightIdArr[i]};
			parameterList.add(paraArr);
		}
		
		IService service = ServiceFactory.getService(null);
		try {
			service.executeBySql("delete from SYSMAN_ROLE_RIGHT where ROLE_ID='" + roleId + "'");
			service.executeBatchBySql("insert into SYSMAN_ROLE_RIGHT(ROLE_ID,RIGHT_ID) values(?,?)", parameterList);
			swt.setValue("1");
		} catch (Exception e) {
			e.printStackTrace();
			swt.setValue("0");
		}
		return swt;
	}
	
	//检查是否登录
	public static void checkLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		if(request.getSession(false) == null) {//session过期
			request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
			return;
		}
		
		@SuppressWarnings("unchecked")
		Map<String, Object> loginUser = (Map<String, Object>) request.getSession().getAttribute(LoginConst.SESSION_USER);
		if(loginUser == null || loginUser.isEmpty()) {//未登录
			request.getRequestDispatcher("/admin/login.jsp").forward(request,response);
		}
	}
}
